import React, { useEffect, useRef, useState } from 'react';
import styles from './index.module.less';
import Paused from '@/assets/AiImgs/paused.png';
import Start from '@/assets/AiImgs/start.png';
import {getTrainRecord} from '@/api/train'
interface Utterance {
  utterances: string;
  start_time: number;
  end_time: number;
}

interface AudioRecord {
  audio_url: string;
  record: Utterance[];
}

interface ApiResponse {
  code: number;
  msg: string;
  data: {
    list: AudioRecord[];
  };
}

const PlayBlack: React.FC = () => {
  const [audioList, setAudioList] = useState<AudioRecord[]>([]);
  const [currentAudioIdx, setCurrentAudioIdx] = useState(0);
  const [currentTime, setCurrentTime] = useState(0);
  const [isPlaying, setIsPlaying] = useState(false);
  const [showSubtitles, setShowSubtitles] = useState(true);
  const audioRef = useRef<HTMLAudioElement>(null);

  
  useEffect(() => {
    getTrainRecord({practice_id:1335})
      .then((data: ApiResponse) => {
        if (data.code === 2000) {
          setAudioList(data.data.list);
        }
      });
  }, []);

  useEffect(() => {
    setCurrentTime(0);
    setIsPlaying(false);
    if (audioRef.current) {
      audioRef.current.currentTime = 0;
      audioRef.current.pause();
    }
  }, [currentAudioIdx]);

  const handleTimeUpdate = () => {
    if (audioRef.current) {
      setCurrentTime(audioRef.current.currentTime * 1000);
    }
  };

  const handlePlayPause = () => {
    if (!audioRef.current) return;
    if (isPlaying) {
      audioRef.current.pause();
      setIsPlaying(false);
    } else {
      audioRef.current.play();
      setIsPlaying(true);
    }
  };

  const currentAudio = audioList[currentAudioIdx];
  const visibleSubtitles = currentAudio?.record.filter(item => item.start_time <= currentTime) || [];

  return (
    <div className={styles.container}>
      <div className={styles.header}>
        <div className={styles.timeDisplay}>
          00:00:{String(Math.floor((currentTime / 1000) % 60)).padStart(2, '0')}
        </div>
        <div className={styles.subtitleControl}>
          <span className={styles.subtitleLabel}>字幕</span>
          <input 
            type="checkbox" 
            checked={showSubtitles}
            onChange={(e) => setShowSubtitles(e.target.checked)}
            className={styles.subtitleCheckbox}
          />
        </div>
      </div>

      {showSubtitles && (
        <div className={styles.subtitleContainer}>
          {visibleSubtitles.map((item, idx) => {
            const isActive = currentTime >= item.start_time && currentTime < item.end_time;
            return (
              <div
                key={item.start_time + '-' + idx}
                className={`${styles.subtitleItem} ${isActive ? styles.active : ''}`}
              >
                {item.utterances}
              </div>
            );
          })}
        </div>
      )}

      <div className={styles.controls}>
        {currentAudio && (
          <>
            <audio
              ref={audioRef}
              src={currentAudio.audio_url}
              onTimeUpdate={handleTimeUpdate}
              onEnded={() => setIsPlaying(false)}
              style={{ display: 'none' }}
            />
            <button
              onClick={handlePlayPause}
              className={styles.playButton}
            >
              <span className={styles.playIcon}>
                {isPlaying ? '⏸️' : '▶️'}
              </span>
              <span className={styles.playText}>开始</span>
            </button>
          </>
        )}
      </div>

      {audioList.length > 1 && (
        <div className={styles.pagination}>
          {audioList.map((_, idx) => (
            <button
              key={idx}
              onClick={() => setCurrentAudioIdx(idx)}
              className={`${styles.paginationDot} ${idx === currentAudioIdx ? styles.active : ''}`}
            />
          ))}
        </div>
      )}
    </div>
  );
};

export default PlayBlack; 